<template>
   <div style="height: 100vh;">
    <div v-if="uploadLoading" class="fullscreen-loading">
      <div class="loading-content">
        <div class="spinner"></div>
        <p>文件解析中，请稍候...</p>
      </div>
    </div>


            <!-- header -->
        <div class="header">
            <div class="header-logo">
            <img src="/assets/headerLogo.png" class="header-img" />
            <div id="header-version"></div>
            </div>
        </div>

        <!-- player -->
         <div class="conversation">
          <div class="player" style="display: none">
            <div class="left-sidebar"></div>
            <div id="player-list">
              <div id="local-player" class="player-wrapper">
                <div id="local-player-name" class="player-name"></div>
              </div>
            </div>
          </div>
           <div class="message-list-container">
            <!-- 消息列表 -->
              <div class="message-list" ref="messageList">
                  <div v-for="(message, index) in messages" :key="index" :class="['message', message.sender]">
                      <div class="message-content" v-html="renderMath(preprocessContent(message.content))"></div>
                  </div>
              </div>
                  
                  <!-- 输入框和发送按钮 -->
              <div class="input-container">
                  <!-- 文件上传按钮 -->
                  <input type="file" id="file-upload" @change="handleFileUpload" accept="image/png, image/jpeg" />
                  <label for="file-upload" class="file-upload-label">上传文件</label>
                  <input v-model="newMessage" placeholder="输入消息..." @keyup.enter="sendMessage" />
                  <button @click="sendMessage">发送</button>
              </div>
            </div>  
         </div>



        <div class="right-panel math-questions-container">
          <div v-if="error" class="error-message">{{ error }}</div>
          <div v-else>
            <div v-for="(question, index) in parsedQuestions" :key="index" class="question-card">
              <div class="question-content" v-html="renderMath(preprocessContent(question.content))"></div>
              <ul class="options-list">
                <li v-for="(option, optIndex) in question.options" :key="optIndex"
                    v-html="renderMath(preprocessContent(option))"></li>
              </ul>
            </div>
          </div>
        </div>

        <!-- control panel -->
        <div class="control" id="control" style="display: none;margin-bottom: 60px;">
            <div class="control-left">
            <div class="control-voice__open control-wrapper" id="control-mic">
                <img src="/assets/micOnIcon.png" alt="" class="control-img" />
            </div>
            <!-- <div class="control-video__open control-wrapper" id="control-video"  style="display: none">
                <img src="/assets/videoOnIcon.png" alt="" class="control-img" />
            </div> -->
            </div>
            <div class="control-right">
            <div class="control-line">
                <div class="control-line__line"></div>
            </div>
            <div class="control-close control-wrapper">
                <img src="/assets/leaveIcon.png" alt="" class="control-img" id="leave" />
            </div>
            </div>
        </div>

        <section class="modal hidden">
            <button class="autoPlayBtn">自动播放</button>
        </section>
        <div class="overlay hidden"></div>
   </div>
</template>

<script setup lang="ts">
import { onMounted,onUnmounted,ref, computed,nextTick } from 'vue';
import { useRouter } from 'vue-router'
import katex from 'katex'
import 'katex/dist/katex.min.css'
import http from '@/api/request';

import AvatarPlatform, {
  PlayerEvents,
  SDKEvents,
} from '@/avatar/index.js'

const messages = ref([
//   { sender: 'remote', content: '你好！' },
//   { sender: 'local', content: '你好，有什么可以帮你的吗？' },
]);

const newMessage = ref('');
const messageList = ref(null);

const router = useRouter()
const userId = localStorage.getItem('username');
const token = localStorage.getItem('token');
const config = {
    appId: localStorage.getItem('appId'),
    roomId: localStorage.getItem('roomId'),
    tokens: [
    {
      userId: userId,
      token: token
    }]
}
const streamOptions = {
  audio: true,
  video: true,
};

let rtc = null;

const error = ref(null)
const questionsData = ref(null)
const uploadLoading = ref(false)

//发送消息
async function sendMessage() {
  if (newMessage.value.trim() !== '') {
    let msg = newMessage.value.trim();
    adavartSpeak(msg)
    // const response = await axios.post(
    //     // "http://localhost:5000/robotAction", 
    //     "/api/proxyAIGCFetch",
    //     {
    //         "AppId": config.appId,
    //         "RoomId": config.roomId,
    //         "TaskId": userId,
    //         "Command":"ExternalPromptsForLLM",    // ExternalTextToLLM
    //         "Message":msg,
    //         "InterruptMode":1,
    //         "command":"ExternalPromptsForLLM",    // ExternalTextToLLM
    //         "message":msg,
    //         "interruptMode":1
    //     },
    //     {
    //         params:{
    //             Action:"UpdateVoiceChat",
    //             Version:"2024-12-01"
    //         }
    //     },
    //     {
    //         headers: {
    //         'Content-Type': 'application/json',
    //         'token':token
    //         }
    //     });

    const response = await http.post(
        "/vertc/proxyAIGCFetch?Action=UpdateVoiceChat",
        {
            "command":"ExternalPromptsForLLM",    // ExternalTextToLLM
            "message":msg,
            "interruptMode":1
        },
        {
            headers: {
            'Content-Type': 'application/json',
            'token':token
            }
        });

    messages.value.push({ sender: 'local', content: newMessage.value.trim() });
    newMessage.value = '';
    nextTick(() => {
      scrollToBottom();
    });
  }
}

const parsedQuestions = computed(() => {
  if (!questionsData.value?.data?.analyseContent) return []

  // 解析题目内容
  const content = questionsData.value.data.analyseContent
  const questionBlocks = content.split(/\n\n(?=\d+\.)/).filter(Boolean)

  return questionBlocks.map(block => {
    const lines = block.split('\n').filter(line => line.trim())
    const content = lines[0]
    const options = lines.slice(1).filter(line => line.trim())

    return {
      content,
      options
    }
  })
})

function preprocessContent(text) {
  // 预处理内容，修复常见的LaTeX语法问题
  return text
      .replace(/\\left\\\{/g, '{')  // 修复多余的\{
      .replace(/\\right\\\}/g, '}') // 修复多余的\}
      .replace(/\\text\{([^}]+)\}/g, '\\$1') // 转换\text{...}为\...
      .replace(/\\mathop\{\\mathrm\{mathbb\}\}/g, '\\mathbb') // 修复\mathbb
      .replace(/\(([a-z]) \)/g, '($1)') // 修复括号内的空格
}

function renderMath(text) {
  if (!text) return ''

  // 处理换行
  const withLineBreaks = text.replace(/\n/g, '<br>')

  // 渲染数学公式
  return withLineBreaks.replace(/\\\(([^]+?)\\\)/g, (match, math) => {
    try {
      return katex.renderToString(math, {
        throwOnError: false,
        displayMode: false,
        macros: {
          '\\text': '\\mathrm{#1}', // 自定义\text宏
          '\\trac': '\\frac{#1}{#2}' // 自定义\trac宏
        }
      })
    } catch (e) {
      console.error('KaTeX渲染错误:', e)
      return `<span class="katex-error">${match}</span>`
    }
  })
}


function handleFileUpload(event) {
  const file = event.target.files[0];
  if (file) {
    // 检查文件类型是否为图片
    const allowedTypes = ['image/png', 'image/jpeg'];
    if (!allowedTypes.includes(file.type)) {
      alert('只能上传png或jpg格式的图片');
      return;
    }

    const formData = new FormData();
    formData.append('file', file);

  error.value = null
  try {
    uploadLoading.value = true
    http.post('/vertc/uploadFileAndAnalyse',formData,{
      headers: {
        'Content-Type': 'multipart/form-data',
        'token':token
      }
    }).then(response => {
      //获取识别结果
      uploadLoading.value = false
      console.log(response.data.data.analyseContent);
      questionsData.value = response.data
      // const myDiv = document.getElementsByClassName('right-panel')[0];
      // myDiv.innerHTML += '<span>'+response.data.data.analyseContent+'</span>';
    });
  } catch (err) {
    console.error('获取题目失败:', err)
    error.value = '加载题目失败，请稍后重试'
  }

//     let msg = `以下是图片中的题目内容：\n\n
// 5. 已知曲线 \\( C: x^2 + y^2 = 16 (y > 0) \\)，从 \\( C \\) 上任意一点 \\( P \\) 向 \\( x \\) 轴作垂线段 \\( PP' \\)，\\( P' \\) 为垂足，则线段 \\( PP' \\) 的中点 \\( M \\) 的轨迹方程为（ ）\nA. \\(\\frac{x^2}{16} + \\frac{y^2}{4} = 1 (y > 0)\\)\nB. \\(\\frac{x^2}{16} + \\frac{y^2}{8} = 1 (y > 0)\\)\nC. \\(\\frac{y^2}{16} + \\frac{x^2}{4} = 1 (y > 0)\\)\nD. \\(\\frac{y^2}{16} + \\frac{x^2}{8} = 1 (y > 0)\\)\n\n6. 设函数 \\( f(x) = a(x+1)^2 - 1 \\)，\\( g(x) = \\cos x + 2ax \\)，当 \\( x \\in (-1, 1) \\) 时，曲线 \\( y = f(x) \\) 与 \\( y = g(x) \\) 恰有一个交点，则 \\( a = \\)（ ）\nA. -1\nB. \\(\\frac{1}{2}\\)\nC. 1\nD. 2\n\n7. 已知正三棱台 \\( ABC - A_1B_1C_1 \\) 的体积为 \\(\\frac{52}{3}\\)，\\( AB = 6 \\)，\\( A_1B_1 = 2 \\)，则 \\( A_1A \\) 与平面 \\( ABC \\) 所成角的正切值为（ ）\nA. \\(\\frac{1}{2}\\)\nB. 1\nC. 2\nD.`;

//     let contents = msg.split("\n");
//     console.log(contents.length);
//     for(let i=0;i<contents.length;i++){
//       let line = contents[i].replace("\\(","\(");
//       line = line.replace("\\)","\)");
//       // line = line.replace(`\frac`,`\\frac`);
//       console.log(line);
//       rightPanelContent.value.push(line);
//     }

    // axios.post('/api/uploadFileAndAnalyse',formData,{
    //   headers: {
    //     'Content-Type': 'multipart/form-data'
    //   }
    // }).then(response => {
    //   //获取识别结果
    //   console.log(response.data.data.analyseContent);
    //   rightPanelContent.value.push(response.data.data.analyseContent);
    //   // const myDiv = document.getElementsByClassName('right-panel')[0];
    //   // myDiv.innerHTML += '<span>'+response.data.data.analyseContent+'</span>';
    // });

    // axios.post('http://localhost:5000/upload', formData, {
    //   headers: {
    //     'Content-Type': 'multipart/form-data'
    //   }
    // })
    // .then(response => {
    //     console.log(response.data);
    //     let data = response.data.result.Data;
    //     let dataobj = JSON.parse(data);
    //     console.log("result object======>",dataobj);

    //     const img = new Image();
    //     img.src = URL.createObjectURL(file);

    //     img.onload = () => {
    //         const canvas = document.querySelector('.right-panel canvas');
    //         const ctx = canvas.getContext('2d');

    //         canvas.width = img.width;
    //         canvas.height = img.height;

    //         ctx.drawImage(img, 0, 0);

    //         ctx.strokeStyle = 'red'; 
    //         ctx.lineWidth = 2;
    //         dataobj.doc_layout.forEach(item => {
    //             let pos = item.pos;
    //             ctx.strokeRect(pos[0].x, pos[0].y, pos[2].x-pos[0].x, pos[1].y-pos[0].y);
    //         });

    //         ctx.strokeStyle = 'blue'; 
    //         dataobj.doc_sptext.forEach(item => {
    //             let pos = item.pos;
    //             ctx.strokeRect(pos[0].x, pos[0].y, pos[2].x-pos[0].x, pos[1].y-pos[0].y);
    //         });

    //         ctx.strokeStyle = 'green';
    //         dataobj.doc_subfield.forEach(item => {
    //             let pos = item.pos;
    //             ctx.strokeRect(pos[0].x, pos[0].y, pos[2].x-pos[0].x, pos[1].y-pos[0].y); 
    //         });

    //         ctx.strokeStyle = 'yellow';
    //         dataobj.figure.forEach(item => {
    //             let pos = item.points;
    //             ctx.strokeRect(pos[0].x, pos[0].y, pos[2].x-pos[0].x, pos[1].y-pos[0].y); 
    //         });

    //         // ctx.strokeStyle = 'red'; // 矩形框颜色
    //         // ctx.lineWidth = 2; // 矩形框线条宽度
    //         // ctx.strokeRect(100, 100, 20, 30); // 矩形框位置和大小
    //     };
    // })
    // .catch(error => {
    //     console.error('文件上传失败:', error);
    // })
  }
}

function scrollToBottom() {
  if (messageList.value) {
    messageList.value.scrollTop = messageList.value.scrollHeight;
  }
}

function handleUserJoin(e) {
  console.log('handleUserJoin', e);
  const { userInfo } = e;
  const remoteUserId = userInfo.userId;
  const currentLength = $('.player-wrapper').length;
  if (currentLength < 4 && remoteUserId == userId) {
    const player = $(`
		<div id="player-wrapper-${remoteUserId}" class="player-wrapper remote-player">
		  <p class="player-name">${remoteUserId}</p>
		</div>
	  `);
    $('#player-list').append(player);
  }
}

function handleUserLeave(e) {
  console.log('handleUserLeave', e);
  const { userInfo } = e;
  const remoteUserId = userInfo.userId;
  $(`#player-wrapper-${remoteUserId}`).remove();
  rtc.checkAutoPlayFailUser(remoteUserId);
}


async function handleUserPublishStream(stream) {
  console.log('handleUserPublishStream', stream);
  const { userId, mediaType } = stream;
  const remoteUserId = userId;
  if (mediaType & rtc.MediaType.VIDEO) {
    const player = $(`#player-wrapper-${remoteUserId}`);
    if (player[0]) {
      rtc.setRemoteVideoPlayer(remoteUserId, player[0]);
    }
  }
}

function handleUserUnpublishStream(stream) {
  const { userId, mediaType } = stream;

  if (mediaType & rtc.MediaType.VIDEO) {
    rtc.setRemoteVideoPlayer(userId, undefined);
  }
}

function handleEventError(e) {
  if (e.errorCode === VERTC.ErrorCode.DUPLICATE_LOGIN) {
    // actionToLeave();
    alert('你的账号被其他人顶下线了');
    // closeModal();
    rtc.autoPlayFailUser = [];

    if (rtc!=null){
        rtc.removeEventListener();
        rtc.leave();
        removeRobot();
    }

    router.push('/login');
  }
}

async function handleUserStartVideoCapture(event) {
  const { userId } = event;
  const player = $(`#player-wrapper-${userId}`);
  if (player[0]) {
    rtc.setRemoteVideoPlayer(userId, player[0]);
  }
}

function handleUserStopVideoCapture(event) {
  const { userId } = event;

  rtc.setRemoteVideoPlayer(userId, undefined);
}

function handleRemoteStreamStats(event){
    // console.log('handleRemoteStreamStats', event);
}
function handleLocalStreamStats(event){
    // console.log('handleLocalStreamStats', event);
}
function handleAudioDeviceStateChanged(event){
    // console.log('handleAudioDeviceStateChanged', event);
}
function handleLocalAudioPropertiesReport(event){
    // console.log('handleLocalAudioPropertiesReport', event);
}
function handleRemoteAudioPropertiesReport(event){
    // console.log('handleRemoteAudioPropertiesReport', event);
}
function handleUserMessageReceived(event){
    // console.log('handleUserMessageReceived', event);
}
function handleUserStartAudioCapture(event){
    // console.log('handleUserStartAudioCapture', event);
}
function handleUserStopAudioCapture(event){
    // console.log('handleUserStopAudioCapture', event);
}

let receivedMsg = "";
let currentUser = "";
let needNewMsg = false;
function handleRoomBinaryMessageReceived(event){
    // console.log('handleRoomBinaryMessageReceived',event);
    const result = tlv2String(event.message);
    const msgResult = JSON.parse(result.value);

    if (result.type === "conv") {
        //接受消息
        if (msgResult.Stage != null) {
            if (msgResult.Stage.Description === "answering") {
                //开始回答
                receivedMsg = "";
                needNewMsg = false;
                messages.value.push({ sender: 'remote', content: '' });
            }
            // if (msgResult.Stage.Description === "answerFinish") {
            //     //结束回答
            //     console.log("1:"+currentUser,receivedMsg);
            //     receivedMsg = "";
            // }
            if (msgResult.Stage.Description === "listening") {
                //接受语音输入
                receivedMsg = "";
                needNewMsg = false;
                messages.value.push({ sender: 'local', content: '' });
            }
            // if (msgResult.Stage.Description === "thinking") {
            //     //语音输入完成，思考中
            //     console.log("2:"+currentUser,receivedMsg);
            //     receivedMsg = "";
            // }
        }
    } else if (result.type === "subv") {
        if (msgResult.data!=null){
            currentUser = msgResult.data[0].userId;

            if (needNewMsg) {
              console.log("currentUser:"+currentUser+",userId:"+userId);
                if (currentUser != userId) {
                    messages.value.push({ sender: 'remote', content: receivedMsg.trim() });
                } else {
                    messages.value.push({ sender: 'local', content: receivedMsg.trim() });
                }

                if (!msgResult.data[0].definite) {
                    receivedMsg = "";
                }
                needNewMsg = false;
            }
            
            let msg = "";
            msgResult.data.forEach((item) => {
                msg += item.text;
            });
            if (msgResult.data[0].definite) { //段落结尾标志
                //如果是重起段落则输出当前文本
                messages.value[messages.value.length - 1].content = receivedMsg.trim();
                needNewMsg = true;
                // console.log("3:"+currentUser,receivedMsg);
            } else { //非段落结尾则直接更新到消息
                receivedMsg = msg;
                messages.value[messages.value.length - 1].content = receivedMsg.trim();
            }
            nextTick(() => {
                scrollToBottom();
            });
        }
    }
}
function handleNetworkQuality(event){
    // console.log('handleNetworkQuality', event);
}       



function tlv2String(tlvBuffer) {
    const typeBuffer = new Uint8Array(tlvBuffer, 0, 4);
    const lengthBuffer = new Uint8Array(tlvBuffer, 4, 4);
    const valueBuffer = new Uint8Array(tlvBuffer, 8);

    let type = '';
    for (let i = 0; i < typeBuffer.length; i++) {
      type += String.fromCharCode(typeBuffer[i]);
    }

    const length =
      (lengthBuffer[0] << 24) | (lengthBuffer[1] << 16) | (lengthBuffer[2] << 8) | lengthBuffer[3];

    const value = new TextDecoder().decode(valueBuffer.subarray(0, length));
    return { type, value };
  }

function setSessionInfo(params) {
  Object.keys(params).forEach((key) => {
    sessionStorage.setItem(key, params[key]);
  });
}

const actionLeave = async () => {
  $('#header-version').text(`RTC版本 v${rtc.SDKVERSION}`);
  $('.remote-player').remove();
  // clear the dom
  $('#user-id').val('');
  $('#room-id').val(config.roomId);
  $('#control').hide();
  $('.player').hide();

  rtc.isMicOn = true;
  rtc.changeMicOrVideoIconUrl('mic', rtc.isMicOn, rtc.OFFMICICON, rtc.ONMICICON);
  rtc.isVideoOn = false;
  rtc.changeMicOrVideoIconUrl('video', rtc.isVideoOn, rtc.OFFVIDEOICON, rtc.ONVIDEOICON);

  // off the event
  rtc.removeEventListener();

  removeLoginInfo();
//   // leave the room
  await rtc.leave();
};

function removeLoginInfo() {
  const variable = ['roomId', 'uid'];
  variable.forEach((v) => sessionStorage.removeItem(v));
}

async function addRobot(){
    // const response = await axios.post(
    //     // "http://localhost:5000/robotAction", 
    //     "/api/proxyAIGCFetch",
    //     {
    //     "AppId": config.appId,
    //     "RoomId": config.roomId,
    //     "TaskId": userId,
    //     "AgentConfig": {
    //         "UserId": "BotName001",
    //         "WelcomeMessage": "你好，我是你的AI小助手，有什么可以帮你的吗？",
    //         "EnableConversationStateCallback": true,
    //         "ServerMessageSignatureForRTS": "conversation",
    //         "TargetUserId": [
    //             userId
    //         ]
    //     },
    //     "Config": {
    //         "LLMConfig":{
    //             "Mode":"ArkV3",
    //             "EndPointId": "ep-20250313132439-v78jg",
    //             "MaxTokens": 1024,
    //             "Temperature": 0.1,
    //             "TopP": 0.3,
    //             "SystemMessages": [
    //                 "##人设\n你是一个全能智能体，拥有丰富的百科知识，可以为人们答疑解惑，解决问题。\n你性格很温暖，喜欢帮助别人，非常热心。\n\n##技能\n1. 当用户询问某一问题时，利用你的知识进行准确回答。回答内容应简洁明了，易于理解。\n2. 当用户想让你创作时，比如讲一个故事，或者写一首诗，你创作的文本主题要围绕用户的主题要求，确保内容具有逻辑性、连贯性和可读性。除非用户对创作内容有特殊要求，否则字数不用太长。\n3. 当用户想让你对于某一事件发表看法，你要有一定的见解和建议，但是也要符合普世的价值观。"
    //             ],
    //             "Prefill": true,
    //             "ModelName": "Doubao-pro-32k",
    //             "ModelVersion": "1.0",
    //             "WelcomeSpeech": "你好，我是你的AI小助手，有什么可以帮你的吗？",
    //             "ModeSourceType": "Available",
    //             "APIKey": "",
    //             "Url": "",
    //             "Feature": "{\"Http\":true}"
    //         },
    //         "TTSConfig":{
    //             "Provider":"volcano",
    //             "ProviderParams":{
    //                 "app":{
    //                     "AppId":"3182081281",
    //                     "Cluster": "volcano_tts",
    //                 },
    //                 "audio": {
    //                     "voice_type": "BV001_streaming",
    //                     "speech_rate": 1,
    //                 }
    //             },
    //             "IgnoreBracketText": [
    //             1,
    //             2,
    //             3,
    //             4,
    //             5]
    //         },
    //         "ASRConfig":{
    //             "Provider":"volcano",
    //             "ProviderParams":{
    //                 "Mode":"smallmodel",
    //                 "AppId":"3182081281",
    //                 "Cluster":"volcengine_streaming_common"
    //             },
    //             "VADConfig": {
    //                 "SilenceTime": 600,
    //                 "SilenceThreshold": 200
    //             },
    //             "VolumeGain": 0.3
    //         },
    //         "InterruptMode":0, //打断模式 1为禁用打断
    //         "SubtitleConfig": {
    //             "SubtitleMode": 0
    //         }
    //     }
    //     },
    // {
    //     params:{
    //         Action:"StartVoiceChat",
    //         Version:"2024-12-01"  
    //     }
    // },{
    //     headers: {
    //         'Content-Type': 'application/json'
    //     }
    // });
    const response = await http.post(
        "/vertc/proxyAIGCFetch?Action=StartVoiceChat",{},
        {
          headers: {
              'Content-Type': 'application/json',
              'token':token
          }
        });
    console.log("添加robot:"+response);
    addAdavart();
}

async function removeRobot() {
    // const response = await axios.post(
    //     // "http://localhost:5000/robotAction", 
    //     "/api/proxyAIGCFetch",
    //     {
    //         "AppId": config.appId,
    //         "RoomId": config.roomId,
    //         "TaskId": userId
    //     },
    //     {
    //         params:{
    //             Action:"StopVoiceChat",
    //             Version:"2024-12-01"
    //         }
    //     },
    //     {
    //         headers: {
    //         'Content-Type': 'application/json',
    //         'token':token
    //         }
    //     });
    removeAdavart();
    const response = await http.post(
        "/vertc/proxyAIGCFetch?Action=StopVoiceChat",{},
        {
          headers: {
              'Content-Type': 'application/json',
              'token':token
          }
        });
    console.log("移除robot:"+response);
}

let avatarPlatform=null;
async function addAdavart(){
  avatarPlatform = new AvatarPlatform() 
  // 可以选择性 按需 进行相关事件监听
  avatarPlatform
      .on(SDKEvents.connected, (initResp: any) => {
        console.log('sdk event: connected', initResp)
      })
      .on(SDKEvents.stream_start, () => {
        console.log('sdk event: stream_start')
      })
      .on(SDKEvents.disconnected, (err: any) => {
        console.log('sdk event: disconnected')
        if (err) {
          console.error('ws link disconnected because of Error')
          console.error(e.code, e.message, e.name, e.stack)
        }
      })
      .on(SDKEvents.asr, (asrData: any) => {
        console.log('sdk event: asr', asrData)
      })
      .on(SDKEvents.nlp, (nlpData: any) => {
        console.log('sdk event: nlp', nlpData)
      })
      .on(SDKEvents.frame_start, (frameData: any) => {
        console.log('sdk event: frameBegin', frameData)
      })
      .on(SDKEvents.tts_duration, (sessionData: any) => {
        console.log('sdk event: duration', sessionData)
      })
      .on(SDKEvents.frame_stop, (frameData: any) => {
        console.log('sdk event: frameEnd', frameData)
      })
      .on(SDKEvents.error, (error: any) => {
        console.log('sdk event: error', error)
      })
      .on(SDKEvents.action_start, (actionData: any) => {
        console.log('sdk event: actionBegin', actionData)
      })
      .on(SDKEvents.action_stop, (actionData: any) => {
        console.log('sdk event: actionEnd', actionData)
      });

    const player = avatarPlatform.player || avatarPlatform.createPlayer()
    player
    // ?.on(PlayerEvents.error, (err: any) => {
    //     console.log('sdk player event: player error', err)
    //     if (err?.code === '700005') {
    //       console.log('sdk player event: player h264 not supported')
    //     }
    //   })
      ?.on(PlayerEvents.play, () => {
        console.log('sdk event: player play')
      })
      .on(PlayerEvents.waiting, () => {
        console.log('sdk event: player waiting')
      })
      .on(PlayerEvents.playing, () => {
        console.log('sdk event: player playing')
      })
      .on(PlayerEvents.playNotAllowed, () => {
        console.log('sdk event: play not allowed, muted play')
      })


  // PlayerEvents 常量枚举
  enum PlayerEvents {
    play = 'play',
    waiting = 'waiting',
    playing = 'playing',
    playNotAllowed = 'not-allowed',
  }

  avatarPlatform
  .setApiInfo({
    appId: 'a7854e67',//到交互平台-接口服务中获取，appid需要发布后使用
    apiKey: 'fabdf4e4de2306652eb05b866b8cf4e9',//到交互平台-接口服务中获取
    apiSecret: 'NDkxOTE2MjMyZTdmODc0OGFmNDgyMzMw',//到交互平台-接口服务中获取
    sceneId: '163092082846732288',// //到交互平台-接口服务中获取，传入“接口服务ID”
    serverUrl: 'wss://avatar.cn-huadong-1.xf-yun.com/v1/interact'
  })
  // 设置全局/连接 参数
  .setGlobalParams({
    avatar_dispatch: { interactive_mode: 0, content_analysis: 0 },
    stream: {
      protocol: 'xrtc',//（必穿）实时视频协议，支持webrtc/xrtc，其中只有xrtc支持透明背景，需参数alpha传1
      alpha: 0,
      bitrate: 1000000,
      fps: 25,
    },
    avatar: {
      avatar_id: '110017006', //授权的形象资源id，到交互平台-接口服务-形象列表中获取已授权的形象
      width: 720,
      height: 1280,
      mask_region: '[0, 0, 1080, 1920]',
      scale: 1,
      move_h: 0,
      move_v: 0,
      audio_format: 1,
    }, 
    tts: {
      vcn: 'x4_xiaozhong', //授权的声音资源id，到交互平台-接口服务-声音列表中获取已授权的声音
      speed: 50,
      pitch: 50,
      volume: 100,
    },
    subtitle: {
      subtitle: 0,
      font_color: '#ffffff',
    },
      background: {
      enabled: false,
      type: 'url',
      data: '',
    },
  })

  //发起连接
  await avatarPlatform
      .start({
        wrapper: document.querySelector('.left-sidebar') as HTMLDivElement
      })
      .then(() => {
        console.log('connected &&  stream play successfully')
      })
      .catch((e: any) => {
        console.error(e.code, e.message, e.name, e.stack)
      })
}

async function removeAdavart(){
  avatarPlatform.stop();
  avatarPlatform.destroy()
}

function adavartSpeak(txt:any){
  avatarPlatform.writeText(txt, {
    nlp: false//nlp语义理解，false为关闭，true为开启。等于true时需要开启交互平台-接口服务-大模型对话中的大模型。
  }).catch(e=> {
    console.log(e)
  })
}


onMounted(async () => {
    rtc = new RtcClient({
        config,
        streamOptions,
        handleUserPublishStream,
        handleUserUnpublishStream,
        handleUserStartVideoCapture,
        handleUserStopVideoCapture,
        handleUserJoin,
        handleUserLeave,
        handleEventError,
        handleRemoteStreamStats,
        handleLocalStreamStats,
        handleAudioDeviceStateChanged,
        handleLocalAudioPropertiesReport,
        handleRemoteAudioPropertiesReport,
        handleUserMessageReceived,
        handleUserStartAudioCapture,
        handleUserStopAudioCapture,
        handleRoomBinaryMessageReceived,
        handleNetworkQuality
    });

    try{
        rtc.bindEngineEvents();
        // let token = localStorage.getItem('token');
        // console.log('token======>>>>'+token);
        await rtc.join(token, config.roomId, userId);
        console.log('join room success!');
        try{
            rtc.createLocalStream();
        }catch(e){console.log(e)}

        setSessionInfo({ roomId: config.roomId, uid: userId });

        $('#header-version').text(`${config.roomId}`);
        if (streamOptions.video) {
            $('.player').show();
            $('#local-player').show();
            $('#local-player-name').text(`${userId}`);
        }
        //  else {
        //     $('#control-video').hide();
        // }
        $('#control').show();
        $('#pannel').hide();
        $('.control-wrapper').show();
        $('#join-res').hide();
        $('#join-res').text('');

        //添加智能体到频道
        addRobot();
    }catch(e){
        console.log(e);
    }

    $('#control-mic').click(async () => {
        rtc.isMicOn = !rtc.isMicOn;
        await rtc.changeAudioState(rtc.isMicOn);
        // toggle the mic icon url
        rtc.changeMicOrVideoIconUrl('mic', rtc.isMicOn, rtc.OFFMICICON, rtc.ONMICICON);
    });

    // $('#control-video').click(async () => {
    //     rtc.isVideoOn = !rtc.isVideoOn;
    //     await rtc.changeVideoState(rtc.isVideoOn);
    //     // // toggle the video icon url
    //     rtc.changeMicOrVideoIconUrl('video', rtc.isVideoOn, rtc.OFFVIDEOICON, rtc.ONVIDEOICON);
    // });


    $('#leave').click(async () => {
        await actionLeave();
        router.push('/login')
    });
});

onUnmounted(() => {
    if (rtc!=null){
        rtc.removeEventListener();
        rtc.leave();
        removeRobot();
    }
});

</script>


<style>
@import "/css/index.css";

.conversation {
  display: inline-block;
  flex-direction: column;
  width: 48%;
  height: 92vh; 
  vertical-align: top;
  background-color: #fefefe;
}

.player {
  height: 33.33vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.left-sidebar {
  position: absolute; /* 绝对定位，脱离文档流 */
  left: 0;
  top: 0;
  width: 240px;
  height: 100%;
  background: rgba(255, 255, 255, 0.9); /* 半透明背景 */
  z-index: 1000; /* 确保在最上层 */
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.2); /* 阴影效果 */
}


#player-list {
  position: relative; 
  z-index: 1;
}

.message-list-container {
  flex: 1; /* 占满剩余的高度 */
  display: flex;
  height: 66%;
  flex-direction: column;
}

.right-panel {
    display: inline-block;
  width: 48%;
  float: right; 
  height: 92vh; 
  vertical-align: top;
  /* background-color: #ffff00; */
  padding: 10px;
  overflow-y: auto;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  /* height: 88vh; */
}

.message {
  margin-bottom: 10px;
  display: flex;
}

.message-content {
  max-width: 70%;
  padding: 10px;
  border-radius: 10px;
  word-wrap: break-word;
}

.message.local .message-content {
  background-color: #dcf8c6;
  margin-left: auto;
}

.message.remote .message-content {
  background-color: #ececec;
  margin-right: auto;
}

.input-container {
  display: flex;
  padding: 10px;
  background-color: #f9f9f9;
  border-top: 1px solid #ddd;
}

.file-upload-label {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-right: 10px; /* 与输入框之间添加间距 */
}

.file-upload-label:hover {
  background-color: #0056b3;
}

#file-upload {
  display: none; /* 隐藏默认的文件上传按钮 */
}

.input-container input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  margin-right: 10px;
}

.input-container button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.input-container button:hover {
  background-color: #0056b3;
}
.math-questions-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Arial', sans-serif;
}

.question-card {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 25px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.question-content {
  font-size: 18px;
  line-height: 1.6;
  margin-bottom: 15px;
}

.options-list {
  list-style-type: none;
  padding-left: 20px;
}

.options-list li {
  margin-bottom: 10px;
  padding: 8px 12px;
  background-color: #fff;
  border-radius: 4px;
  border-left: 3px solid #4CAF50;
}

.error-message {
  color: #f44336;
  text-align: center;
  padding: 20px;
  background-color: #ffebee;
  border-radius: 4px;
}

.katex-error {
  color: red;
  font-weight: bold;
}


.fullscreen-loading {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-content {
  background: white;
  padding: 30px;
  border-radius: 8px;
  text-align: center;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 15px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>